package com.chris.core.socket.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义netty http handler
 */
public class NettyHttpHandler extends SimpleChannelInboundHandler<HttpObject> {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
       if (msg instanceof HttpRequest)
       {
           log.debug("msg："+msg.getClass());
           log.debug("客户端地址："+ctx.channel().remoteAddress());

           ByteBuf byteBuf = Unpooled.copiedBuffer("hello world",CharsetUtil.UTF_8);

           FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,byteBuf);
           response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
           response.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());

           ctx.writeAndFlush(response);
       }
    }
}
